package com.lm.spi.loader;

import lombok.var;

import java.util.ArrayList;
import java.util.List;

public class CustomServiceLoader<T> {

    private Class<T> service;

    public CustomServiceLoader(Class<T> service) {
        this.service = service;
    }

    public List<T> loadServices() {
        List<T> services = new ArrayList<>();
        String serviceFile = "META-INF/services/" + service.getName();
        try {
            // 从 classpath 加载配置文件
            var resources = Thread.currentThread().getContextClassLoader().getResources(serviceFile);
            while (resources.hasMoreElements()) {
                var url = resources.nextElement();
                try (var reader = new java.io.BufferedReader(new java.io.InputStreamReader(url.openStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        line = line.trim();
                        if (!line.isEmpty()) {
                            // 动态加载类
                            Class<?> clazz = Class.forName(line);
                            services.add(service.cast(clazz.getDeclaredConstructor().newInstance()));
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return services;
    }
}
